package com.karry.yl.web.food;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.PDFGenerator;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.food.FoodModel;
import com.karry.yl.service.food.FoodService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 菜谱管理Controller
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/foodManage")
public class FoodController extends SuperController {

    @Autowired
    private FoodService foodService;

    /**
     * 到报修列表页
     *
     * @return
     */
    @RequestMapping
    public String listUI() {
        return "food/menu/list";
    }

    @RequestMapping("/add")
    public String addUI(ModelMap map) {
        return "food/menu/add";
    }

    @RequestMapping("edit")
    public String editUI(Long id, ModelMap map) {
        FoodModel foodModel = foodService.selectById(id);
        map.put("foodModel", foodModel);
        return "food/menu/edit";
    }


    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit) {
        Page<FoodModel> foodPage = foodService.selectPage(new Page<FoodModel>(page, limit), new EntityWrapper<FoodModel>().eq("orgId", currentUser.getOrgId()).orderBy("foodDate",true));
        return new LayTableResponse(foodPage.getRecords(), foodPage.getTotal());
    }

    @RequestMapping("/save")
    public String save(String[] foodDate, String[] foodName, String[] foodBurden, String[] foodTime, String[] createUserName) {
        ArrayList<FoodModel> foodList = new ArrayList<FoodModel>();
        for (int i = 0; i < foodDate.length; i++) {
            FoodModel food = new FoodModel();
            food.setOrgId(currentUser.getOrgId());
            food.setFoodDate(foodDate[i]);
            food.setFoodName(foodName[i]);
            food.setFoodBurden(foodBurden[i]);
            food.setFoodTime(foodTime[i]);
            food.setCreateUserName(createUserName[i]);
            foodList.add(food);
        }
        foodService.insertList(foodList);
        return "redirect:/foodManage";
    }

    @RequestMapping("/update")
    public String update(FoodModel foodModel) {
        foodModel.setOrgId(currentUser.getOrgId());
        foodService.updateById(foodModel);
        return "redirect:/foodManage";
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping(path = "/delete")
    public String delete(@RequestParam("id") List<Long> ids) {
        foodService.deleteBatchIds(ids);
        return "redirect:/foodManage";
    }

    /**
     * 导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response, String startDate, String endDate) {
        //查询时间段菜谱
        List<FoodModel> foods = foodService.selectList(new EntityWrapper<FoodModel>().eq("orgId", currentUser.getOrgId()).between("foodDate",startDate,endDate));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("餐谱");
        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        //声明列对象
        HSSFCell cell = null;
        //创建标题
        String[] title = {"餐谱日期", "用餐时间", "餐谱名", "配料", "厨师"};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }
        //创建内容
        for (int i = 0; i < foods.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            sheet.setColumnWidth(i + 1, 21 * 256);
            FoodModel foodModel = foods.get(i);
            row.createCell(0).setCellValue(foodModel.getFoodDate());
            row.createCell(1).setCellValue(foodModel.getFoodTime());
            row.createCell(2).setCellValue(foodModel.getFoodName());
            row.createCell(3).setCellValue(foodModel.getFoodBurden());
            row.createCell(4).setCellValue(foodModel.getCreateUserName());
        }
        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("餐谱-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/export/pdf")
    public void exportPdf( HttpServletResponse response, String startDate, String endDate) {
            //生成PDF
            Map<String, Object> model = new HashMap<String,Object>();
            PDFGenerator gen = new PDFGenerator("templates/food/menu/", ".html");
            //查询时间段菜谱
            List<FoodModel> foods = foodService.selectList(new EntityWrapper<FoodModel>().eq("orgId", currentUser.getOrgId()).between("foodDate",startDate,endDate));
            model.put("foods", foods);
            //下载
            response.setCharacterEncoding("UTF-8");
            try (ServletOutputStream out = response.getOutputStream();) {
                response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("菜谱记录" + "-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".pdf", "UTF-8"));
                gen.generate("foodpdf", model, out);
            } catch (Exception e) {
                //TODO 下载失败日志记录
            }
        }
}
